// 引入接口文件
import { getPromoteList, queryAllAddress, houseListGet,exportFile} from './recommendClientsServ'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import {isEmpty, isArray, cloneDeep, merge} from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
import config from 'config/config';
import { download,makeAddress } from 'utils/util'


const queryList = [
  { name: '省市', type: 'cascader', list: [], key: 'district', value: []},
  {name: '推荐楼盘', type: 'text', key: 'productName', value: ''},
  {
    name: '推荐状态', type: 'select', key: 'recommendStatus', value: '', notNeedAll: true, list: [
      {id: '', name: '全部'},
      {id: '0', name: '失败'},
      {id: '1', name: '成功'},
    ]
  },
  {//已提交 已跟进 已到访 已认筹  已认购  已签约 已计佣  已发佣 已关闭
    name: '客户状态', type: 'select', key: 'clientStatus', value: '', notNeedAll: true, list: [
      {id: '', name: '全部'},
      {id: '10', name: '已提交'},
      {id: '20', name: '已跟进'},
      {id: '30', name: '已到访'},
      {id: '40', name: '已认筹'},
      {id: '50', name: '已认购'},
      {id: '60', name: '已签约'},
      {id: '70', name: '已计佣'},
      {id: '80', name: '已发佣'},
      {id: '90', name: '已关闭'},
    ]
  },
  {name: '推荐人姓名', type: 'text', key: 'name', value: ''},
  {name: '推荐人电话', type: 'text', key: 'referrerMobile', value: ''},
  {name: '客户姓名', type: 'text', key: 'customerName', value: ''},
  {name: '客户电话', type: 'text', key: 'mobile', value: ''},
  { name: '推荐时间', type: 'date', key: 'date', value: [] ,options: { format: 'YYYY-MM-DD',width:'500' }},
]

// 初始默认状态
const defultState = {
  exportLoading: false,
  loading: false,
  btnLoading: false,
  queryList,
  currentItem: {},
  modalObj:{
    visible:false,
  },
  productSelf: [],
  productIds: [],
  // 表格数据
  tableData: {
    dataSource: [

    ],
    total: 0,
    stop:0,
    start:0
  },
  // 表格分页设置
  pageConfig: {
    pageSize: Number.parseInt(config.smallPageSizeList[0]),
    pageNo: 1,
  },

}

// 声明module
const tmpModule = {
  // namespace: 'productListModel',
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({ pathname, query }) => {
        // 页面路由匹配时执行
        if('' + tmpModule.pathname === '' + pathname){
          // dispatch({ type: 'updateStore', payload: {...cloneDeep(defultState), ...query} });//每次进去页面先重置状态
          // 执行业务操作
          // dispatch({type: 'search', payload: {}}) ;// end dispatch
          dispatch({ type: 'getAreaList', payload: {} });
        } // end if
      }) // end listen
    },
  },

  // 方法列表
  effects: {
    //查询操作
    * search ({payload = {}}, {call, put, select}) {
      let {queryList, tableData, pageConfig, productIds} = yield select(state => state[tmpModule.namespace])
      const pageSize = pageConfig.pageSize
      
      //组装接口入参
      let params = {
        productIds: isEmpty(productIds) ? null : productIds,
        startTime: null,
        endTime: null,
        province: null,
        city: null,
      }
    
      queryList.map(item => {
        let {key = null, value = null} = item
        if (value === '') {value = null}//如果没有值，置为null
        if (item.key == 'date') {
          if (!isEmpty(value)) {
            params.startTime = value[0]
            params.endTime = value[1]
          }
        }
        else if (item.key == 'district') {
          if (!isEmpty(value)) {
            let [province = '', city = '',] = value
            params.province = province
            params.city = city
          }
        }
        else {
          params[item.key] = value
        }
      })
      //显示loading状态
      yield put({type: 'updateStore', payload: {loading: true, btnLoading: true,}})
  
      const {rows, success, msg, total, pageNo} = yield call(getPromoteList, {
        ...params,
        pageNo: payload.pageNo || 1,
        pageSize,
      })
      yield put({type: 'updateStore', payload: {loading: false, btnLoading: false,}})
  
      //console.log('数据', rows, success, msg, total, pageNo)
      if (!success) {
        message.error(msg)
        return false
      }
      let list = rows
      list.map((item, index) => {
        item.key = index + 1
      })
      tableData = {
        dataSource: list,
        total: Number(total)
      }
      yield put({
        type: 'updateStore', payload: {
          pageConfig: {...pageConfig, ...payload},
          tableData,
        }
      })
    },
    *pageChange({ payload }, { put, select }) {
      const { pageNo, pageSize } = payload;
      const { pageConfig } =yield select(state => state[tmpModule.namespace])
      yield put({ type: 'updateStore', payload: { pageConfig: { ...pageConfig, ...payload } } });
      yield put({ type: 'search', payload: { pageNo, pageSize } });
    },
    // 查询条件重置
    *queryReset({ }, { put }) {
      yield put({ type: 'updateStore', payload: { queryList: cloneDeep(queryList),productIds:null } });
      yield put({ type: 'search' })
      yield put({ type: 'getAreaList' })
    },
    //改变查询条件
    *inputChange({ payload }, { call, put, select }) {
      let { queryList } = yield select(state => state[tmpModule.namespace])
      const { key, value } = payload;
      let data = queryList.find(item => item.key === key);
      data.value = value;
      yield put({ type: 'updateStore', payload: { queryList: [...queryList, ...data] } });
      if(key=='district'){
        if(!value||(value.length<2)){return false}
        let [province,city,]=value
        yield put({ type: `houseListGet`, payload: {province,city } });
      }
      
    },

    //获取级联列表
    *getAreaList({ payload }, { put, call, select }) {
      let { queryList ,} = yield select(state => state[tmpModule.namespace])
      try {
        const { data, success } = yield call(queryAllAddress);
        if (success) {
          let areaList = []
          let arr = [data[0]]
          let attr = [data[data.length - 1]]
          data[0] = {
            label: "北京",
            value: "110100",
            children: arr
          }
          data[data.length - 1] = {
            label: "澳门",
            value: "820000",
            children: attr
          }
          //去掉第三级，
          areaList = makeAddress(data,2)
          queryList[0].list=areaList
          yield put({ type: 'updateStore', payload: { queryList } });
        }
      } catch (e) {
      
      }
    },
    //获取项目列表
    *houseListGet({ payload }, { put, call, select }) {
      try {
        const { success, rows } = yield call(houseListGet, { ...payload, pageSize: 10000 })
        if (success) {
          let productIds = [];
          for (let item of rows) {
            productIds.push(item.productId);
          }
          productIds=isEmpty(productIds)?null:productIds,
          yield put({ type: 'updateStore', payload: { productIds: productIds } })
        }
      } catch (e) {
        console.log(e)
      }
    },
  
    //下载模板
    * exportFile ({payload}, {put, call, select}) {
      let {queryList,productIds,pageConfig} = yield select(state => state[tmpModule.namespace])
      //组装接口入参
      let {pageNo=1,pageSize=10}=pageConfig
      pageNo=1
      pageSize=15000
      //组装接口入参
      let params = {
        productIds,
        pageNo,
        pageSize,
        startTime:null,
        endTime:null,
        province:null,
        city:null,
      };
  
      queryList.map(item => {
        let {key=null,value=null}=item
        if(value===''){value=null}//如果没有值，置为null
        if(item.key=='date'){
          if(!isEmpty(value)){
            params.startTime=value[0]
            params.endTime=value[1]
          }
        }
        else if(item.key=='district'){
          if(!isEmpty(value)){
            let [province='',city='',]=value
            params.province=province
            params.city=city
          }
        }
        else{
          params[item.key] = value;
        }
      });
      yield put({ type: 'updateStore', payload: {exportLoading:true}});
      let {data = {}, success, msg} = yield call(exportFile, {...params})
      yield put({ type: 'updateStore', payload: {exportLoading:false}});
      if (!success) {
        // message.error(msg)
        return false
      }
      download(data)
    },
  },

  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
